﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fred
{
    /// <summary>
    /// The Service Factory. Pleas use the singleton provided to Access
    /// </summary>
    public class ServiceFactory
    {
        #region Singleton implementation

        /// <summary>
        /// Instance placeholder
        /// </summary>
        private static ServiceFactory _instance = null;

        /// <summary>
        /// Get the instance
        /// </summary>
        public static ServiceFactory Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new ServiceFactory();

                return _instance;
            }
        }

        #endregion

        #region Service related - Start and Stop

        private List<Services.Service> _services = new List<Services.Service>();

        /// <summary>
        /// Start all the found services
        /// </summary>
        public void Start()
        {
            // Discover all services and fill the list
            // TODO

            // Start them all
            foreach (var service in _services)
            {
                service.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Stop all the found services
        /// </summary>
        public void Stop()
        {
            // First loop - Request all services to stop
            foreach (var service in _services)
            {
                service.CancelAsync();
            }

            // Wait 3 seconds, by then they should have stopped
            System.Threading.Thread.Sleep(3000);

            // First loop - Dispose all services
            foreach (var service in _services)
            {
                service.Dispose();
            }

            _services = new List<Services.Service>();
        }

        #endregion
    }
}
